
package com.axc.gallery2.net;

import java.util.Set;
import java.util.TreeSet;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Parcel;
import android.os.Parcelable;
import android.util.Log;
import android.webkit.WebView;

import com.axc.gallery2.Utils;
import com.renren.api.connect.android.Util;

/**
 * 封装对人人网的上传相册请求
 */
public class RequestRenRen implements Parcelable {

    public static final String DEFAULT_REDIRECT_URI = "http://graph.renren.com/oauth/login_success.html";

    public static final String WIDGET_CALLBACK_URI = "http://widget.renren.com/callback.html";

    private static final String RESTSERVER_URL = "http://api.renren.com/restserver.do";

    private static final String KEY_API_KEY = "api_key";

    private static final String KEY_SECRET = "secret";

    private static final String KEY_APP_ID = "appid";

    private String apiKey;

    private String secret;

    private String appId;

    private AccessTokenManager accessTokenManager;

    private static final String LOG_TAG = "Renren";

    /**
     * 构造Renren对象，开发者可以使用该类调用人人网提供的接口。
     * 
     * @param apiKey
     * @param secretKey
     * @param appId
     */
    public RequestRenRen(String apiKey, String secret, String appId, Context context) {
        if (apiKey == null) {
            throw new RuntimeException("apiKey必须提供");
        }
        if (secret == null) {
            throw new RuntimeException("secret必须提供");
        }
        if (appId == null) {
            throw new RuntimeException("appId必须提供");
        }
        this.apiKey = apiKey;
        this.secret = secret;
        this.appId = appId;
        init(context);
    }

    /**
     * 初始化
     * 
     * @param context
     */
    public void init(Context context) {
        if (context
                .checkCallingOrSelfPermission(Manifest.permission.ACCESS_NETWORK_STATE) != PackageManager.PERMISSION_GRANTED) {
            Log.w(LOG_TAG,
                    "App miss permission android.permission.ACCESS_NETWORK_STATE! "
                    + "Some mobile's WebView don't display page!");
        } else {
            WebView.enablePlatformNotifications();
        }
        this.accessTokenManager = new AccessTokenManager(context);
        this.accessTokenManager.restoreSessionKey();
    }

    /**
     * 上传照片到指定的相册。
     * 
     * @param albumId
     * @param photo
     * @param fileName
     * @param description
     * @param format
     * @return
     */
    public String publishPhoto(long albumId, byte[] photo, String fileName,
            String description, String format) {
        Bundle params = new Bundle();
        params.putString("method", "photos.upload");
        params.putString("aid", String.valueOf(albumId));
        params.putString("caption", description);

        String contentType = parseContentType(fileName);
        params.putString("format", format);
        if (isSessionKeyValid()) {
            params.putString("session_key", accessTokenManager.getSessionKey());
        }
        this.prepareParams(params);
        return Utils.uploadFile(RESTSERVER_URL, params, "upload", fileName,
                contentType, photo);
    }

    /**
     * 判断sessionKey是否有效。
     * 
     * @return boolean
     */
    public boolean isSessionKeyValid() {
        return this.accessTokenManager.isSessionKeyValid();
    }

    /*
     * public String publishPhoto(long albumId, byte[] photo, String fileName,
     * String description, String format) { Bundle params = new Bundle();
     * params.putString("method", "photos.upload"); params.putString("aid",
     * String.valueOf(albumId)); params.putString("caption", description);
     * System.out.println("gzip no. 4"); String contentType =
     * parseContentType(fileName); params.putString("format", format); if
     * (RequestRenRen.isSessionKeyValid()) { System.out.println("gzip no. 5");
     * params.putString("session_key", accessTokenManager.getSessionKey());
     * System.out.println("gzip no. 6"); } System.out.println("gzip no. 7");
     * this.prepareParams(params); return Utils.uploadFile(RESTSERVER_URL,
     * params, "upload", fileName, contentType, photo); }
     */

    private String parseContentType(String fileName) {
        String contentType = "image/jpg";
        fileName = fileName.toLowerCase();
        if (fileName.endsWith(".jpg"))
            contentType = "image/jpg";
        else if (fileName.endsWith(".png"))
            contentType = "image/png";
        else if (fileName.endsWith(".jpeg"))
            contentType = "image/jpeg";
        else if (fileName.endsWith(".gif"))
            contentType = "image/gif";
        else if (fileName.endsWith(".bmp"))
            contentType = "image/bmp";
        else
            throw new RuntimeException("不支持的文件类型'" + fileName + "'(或没有文件扩展名)");
        return contentType;
    }

    private void prepareParams(Bundle params) {
        params.putString("api_key", apiKey);
        params.putString("v", "1.0");
        params.putString("call_id", String.valueOf(System.currentTimeMillis()));
        params.putString("xn_ss", "1");// sessionSecret作为加密密钥

        StringBuffer sb = new StringBuffer();
        Set<String> keys = new TreeSet<String>(params.keySet());
        for (String key : keys) {
            sb.append(key);
            sb.append("=");
            sb.append(params.getString(key));
        }
        sb.append(accessTokenManager.getSessionSecret());
        params.putString("sig", Util.md5(sb.toString()));
    }

    @Override
    public int describeContents() {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        Bundle bundle = new Bundle();
        if (apiKey != null) {
            bundle.putString(KEY_API_KEY, apiKey);
        }
        if (secret != null) {
            bundle.putString(KEY_SECRET, secret);
        }
        if (appId != null) {
            bundle.putString(KEY_APP_ID, appId);
        }
        bundle.writeToParcel(dest, flags);
        this.accessTokenManager.writeToParcel(dest, flags);

    }

}
